package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.context.BaseContext;
import com.example.entity.Account;
import com.example.entity.Buyer;
import com.example.exception.CustomException;
import com.example.mapper.BuyerMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BuyerService {

    @Resource
    private BuyerMapper buyerMapper;
    //登录
    public Buyer login(Account account) {
        String username = account.getUsername();
        Buyer dbBuyer = buyerMapper.selectByUsername(username);
        if(dbBuyer == null){//没有这个用户
            throw new CustomException("500","账号不存在");
        }
        String password = account.getPassword();
        if(!dbBuyer.getPassword().equals(password)){
            throw new CustomException("500","账号或密码错误");
        }
        return dbBuyer;
    }

    public List<Buyer> selectAll(Buyer buyer) {
        return buyerMapper.selectAll(buyer);
    }

    public Buyer selectById(Integer id) {return  buyerMapper.selectById(id);
    }



    public PageInfo<Buyer> selectPage(Buyer buyer, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Buyer> list = buyerMapper.selectAll(buyer);
        return PageInfo.of(list);
    }

    public void add(Buyer buyer) {
        String username = buyer.getUsername();
        Buyer dbBuyer = buyerMapper.selectByUsername(username);
        if(dbBuyer != null){//有这个用户
            throw new CustomException("500","账号已存在");
        }
        buyer.setRole("BUYER");
        buyerMapper.insert(buyer);
    }
    //注册
    public void register(Account account) {

        if (account.getConfirmPassword().equals(account.getPassword())){
            Buyer buyer = new Buyer();
            buyer.setPhone(account.getPhone());
            buyer.setPassword(account.getPassword());
            buyer.setTransactionLocation(account.getTransactionLocation());
            buyer.setUsername(account.getUsername());
            this.add(buyer);
        }else{
            throw new CustomException("500","两次输入的密码不一致");
        }
    }


}
